package com.lse_api.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lse_api.config.multipledatasources.DataSourceContextHolder;
import com.lse_api.entity.LseUserRole;
import com.lse_api.entity.Token;
import com.lse_api.entity.Users;
import com.lse_api.service.LseUserRoleService;
import com.lse_api.service.TokenService;
import com.lse_api.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户鉴权
 *
 * @author 祁雪
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LseUserRoleService lseUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DataSourceContextHolder.setDB(DataSourceContextHolder.DEFAULT_DS);
        // 此处username为LSE token
        QueryWrapper<Token> tokenQueryWrapper = new QueryWrapper<>();
        tokenQueryWrapper.eq("info", username);
        Token token = tokenService.getOne(tokenQueryWrapper);
        if (token == null) {
            return null;
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        List<LseUserRole> lseUserRoles = lseUserRoleService.getUserRoles(token.getUsersUid());

        // 每个权限前需要加 ROLE_ 否则会验证失败 请求权限设置则可不必加ROLE_
        lseUserRoles.forEach(lseUserRole -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                    lseUserRole.getLseRole().getLseRolePermission().getLsePermissions().getName()
            );

            grantedAuthorities.add(grantedAuthority);
        });

        // 返回信息把 userid 注入到用户名中 把token信息注入到password中 grantedAuthorities代表权限列表
        return new User(token.getUsersUid(), token.getInfo(), grantedAuthorities);
    }

}
